<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Serialize方法</title>
  </head>

  <body>
    <form id="form">
      <p><input type="text" name="username"></p>
      <p><input type="text" name="password"></p>
      <p><input type="submit" value="提交"></p>
    </form>
  </body>
  <script src="../js/jquery.min.js"></script>
  <script>
    $("#form").on('submit', function () {
      // 1.将表单内容拼接成字符串类型的参数
      // let str = $("#form").serialize();
      // console.log(str); //username=123&password=456
      let res = serializeObject($(this));
      console.log(res);
      return false;
    })
    // 2.将表单内容转换为数组对象
    function serializeObject(obj) {
      //3.jquery里面有将表单对象转换为数组对象的方法
      let arr = obj.serializeArray();
      // console.log(arr);
      /* [{
          name: "username",
          value: "123"
        },
        {
          name: "password",
          value: "456"
        }
      ] */
      // 4.遍历数组,将数组转换为对象类型
      let returnObj = {};
      $.each(arr, (index, value) => {
        // console.log(index);
        // console.log(value); //{name: "username", value: "123"}
        returnObj[value.name] = value.value;
      })
      // console.log(returnObj);
      return returnObj;
    }
  </script>

</html>